package com.ziroom.zifamily.zfcensor.common.config.idgenerator;

import com.ziroom.zifamily.base.ZfIdGenerator;
import com.ziroom.zifamily.zfcensor.zk.ZkClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

/**
 * <p>TODO</p>
 * <p>
 * <PRE>
 * <BR>    修改记录
 * <BR>-----------------------------------------------
 * <BR>    修改日期         修改人          修改内容
 * </PRE>
 *
 * @author cuiyh9
 * @version 1.0
 * @Date Created in 2018年11月30日 16:37
 * @since 1.0
 */
@Slf4j
@SpringBootConfiguration
public class IdGeneratorConfig {

    @Autowired
    private ZkClient zkClient;

    @Value("${idgenerator.zookeeper.parent.path}")
    private String idgeneratorParentPath;

    @Bean
    public ZfIdGenerator idGenerator() {
        boolean flag = zkClient.createParent(idgeneratorParentPath);
        if (!flag) {
            throw new RuntimeException("创建发号器父节点失败");
        }

        // 获取workId
        long workId = 0;
        long maxWorkNum = ZfIdGenerator.getMaxWorkNum();
        for (long i = 1; i < maxWorkNum; i++) {
            String workPath = idgeneratorParentPath + "/" + i;
            flag = zkClient.createNotExistEphemeralNode(workPath);
            if (flag) {
                workId =  i;
                break;
            }
        }

        if (workId == 0) {
            throw new RuntimeException("获取机器id失败");
        }
        log.warn("idGenerator workId:{}", workId);
        return ZfIdGenerator.getDistributedIdGenerator(workId);

    }
}
